$NG.AllReady(function (page, { useValuesChange,useDataIndexChange,useUpdateRows,useUpdateRow,useBeforeClick }) {
    //获取控件,
    var mstfrom = $NG.getCmpApi("p_form_tenancy_m");
    var grid = $NG.getCmpApi("p_form_tenancy_d");
    if(page.oType =='add'){
        $NG.updateState((updater)=>{
            updater.data.p_form_tenancy_m.setProps({
                bill_name:'租房申请',
                u_ywlx:'租凭费'
            })
        })
    }

    useValuesChange(({args})=>{
        console.log(`项目监听`,args);
        getProjectInfo()
    },"p_form_tenancy_m.phid_pc")
    window.__cache_lsz_count_per = 0
    useUpdateRows(({args})=>{
        const arr = args[0]
        // 计算总价
        // arr.forEach(item=>{
        //     item.u_total = (Number(item.u_rent_prc)||0)*(Number(item.u_month)||0)+(Number(item.u_taxe_amt)||0)+(Number(item.u_zj_amt)||0)
        // })
        // 汇总总价，如果总价无变化则不更改节省性能
        console.log(`触发`);
        let _count_per = 0
        arr.forEach(item=>{
            if(!item.taxrate){
                item.taxrate=0
            }
            _count_per+=(Number(item.u_sjrzrs) || 0)
        })
        if(window.__cache_lsz_count_per!=_count_per){
            window.__cache_lsz_count_per = _count_per
            $NG.updateState((updater)=>{
                updater.data.p_form_tenancy_m.setProps({
                    u_rz_qyt:_count_per
                })
            })
        }
        let _count_total_amt = arr.reduce((value,item)=>{
            return value+(Number(item.u_total))
        },0)
        if(window.__cache_lsz?.total_amt!=_count_total_amt){
            if(!window.__cache_lsz){
                window.__cache_lsz={}
            }
            window.__cache_lsz.total_amt = _count_total_amt
            $NG.updateState((updater)=>{
                updater.data.p_form_tenancy_m.setProps({
                    u_sq_amt:_count_total_amt
                })
            })
        }
        grid.refreshView()
    },"p_form_tenancy_d")
    useUpdateRow(({args})=>{
        console.log(`监听start`,args,args[0].u_start_dt,args[0].u_end_dt);
        // if(args[0].u_start_dt&&args[0].u_end_dt){
        //     console.log(`计算`,sumDate(args[0].u_start_dt,args[0].u_end_dt));
        //     args[0].u_month = sumDate(args[0].u_start_dt,args[0].u_end_dt)
        // }
        args[0].u_total = (Number(args[0].u_rent_prc)||0)*(Number(args[0].u_month)||0)+(Number(args[0].u_taxe_amt)||0)+(Number(args[0].u_zj_amt)||0)
        grid.refreshView()
        console.log(`监听`,args);
    },"p_form_tenancy_d")
    useDataIndexChange(({args})=>{
        getFynameByFyno(args[0].u_cost_pcno,(data)=>{
            args[0].u_cost_pcname = data.u_name
            grid.refreshView()
        })
    },"u_cost_pcno")

    zhufangbiaozhun(["u_city","u_floor"])
    function zhufangbiaozhun(arr){
        arr.forEach(item=>{
            useDataIndexChange(({args})=>{
                const city_phid = args[0].u_city
                const ceng = args[0].u_floor
                if(city_phid&&ceng){
                    $NG.execServer('getRentalStandardsByCity',{city_phid}, function(res){
                        console.log(`住房`,res, city_phid, ceng);
                        if(res.count == 0) return
                        const _data = JSON.parse(res.data)[0].extendObjects
                        if(ceng == '1'){
                            args[0].u_bzbz = _data.u_gcwybz
                        } else {
                            args[0].u_bzbz = _data.u_dcwybz
                        }
                        args[0].u_zfbz = _data.u_bz
                        args[0].u_city_type=_data.u_cslb
                        grid.refreshView()
                    })
                }
                
            },item)
        })
    }
    amtReduce(["u_zfbz","u_rent_prc","u_month","u_rent_prc","u_amt_vat","amt","taxrate","u_taxe_amt"])
    function amtReduce(arr){
        arr.forEach(item=>{
            useDataIndexChange(({args})=>{
                amtReduce_d(args)
            },item)
        })
    }
    function amtReduce_d(args){
        const row = args[0];
		//房租含税
		row.u_amt_vat = (Number(row.u_rent_prc) || 0) * (Number(row.u_month) || 0);
		//房租未税
		row.amt = (Number(row.u_amt_vat) || 0) / (1 + Number(row.taxrate));
		//税额
		row.u_taxe_amt = Number(row.u_amt_vat) - Number(row.amt);
        //重新计算总额
		args[0].u_total = (Number(args[0].u_rent_prc)||0)*(Number(args[0].u_month)||0)+(Number(args[0].u_taxe_amt)||0)+(Number(args[0].u_zj_amt)||0)
		grid.refreshView();
    }
    // useDataIndexChange(({args})=>{
    //     insertMonth(args[0])
    // },"u_start_dt")
    // useDataIndexChange(({args})=>{
    //     insertMonth(args[0])
    // },"u_end_dt")
    //赋值yun月份
    function insertMonth(args){
        if(args.u_start_dt&&args.u_end_dt){
            args.u_month = sumDate(args.u_start_dt,args.u_end_dt)
        }
    }
    getProjectInfo();
	// 获取项目
	function getProjectInfo(phid=mstfrom.getItem("phid_pc").getValue(),lock = false) {
		if (!phid) return;
		$NG.execServer("getPtInfoByPhid", {phid}, (res) => {
			const _data = JSON.parse(res.data)[0].extendObjects;
			console.log(`获取项目信息`, _data);
			$NG.updateState((updater) => {
				updater.data.p_form_tenancy_m.setProps({
					u_pc_no: _data.pc_no, //项目编码    
					u_fycdgs: {
						//事业部or组织
						value: _data.org_phid,
						label: _data.org_name,
					},
                    u_account_company: {
						//事业部or组织
						value: _data.org_phid,
						label: _data.org_name,
					},
					u_regional_center: {
						//区域中心
						value: _data.regional_center_phid,
						label: _data.regional_center_name,
					},
					u_fycd_dept: {
						//部门
						value: _data.dept_phid,
						label: _data.dept_name,
					},
                    u_project_manager:{
                        label:_data.project_manager_name,
                        value:_data.project_manager_phid
                    },
                    
				});
			});
            if(lock){
                return _data
            }
		});
	}



    //判断预期日期是否合理
    // 传入开始时间和结束时间字符串，传入一个回调函数用来清空时间字段：()=>{ 清空逻辑 }
    //示例
    useValuesChange(({args})=>{
        isDate(mstfrom.getItem("bill_dt").getValue(), mstfrom.getItem("u_end_dt").getValue(), ()=>{
            $NG.updateState((updater)=>{
                updater.data.p_form_tenancy_m.setProps({
                    u_end_dt:null
                })
            })
        })
    },"p_form_tenancy_m.u_end_dt")
    function isDate(startDate, endDate, fun){
        try{
            const sDate = new Date(startDate).getTime()
            const eDate = new Date(endDate).getTime()
            let time = eDate-sDate
            if(time<0){
                if(!fun){
                    $NG.alert("报错函数：isDate，没有传入回调函数！")
                }else{
                    $NG.alert("预计结束时间不得小于申请时间")
                    fun()
                }
            }
        }catch(err){
            $NG.alert("报错函数：isDate，传入的字符串不合法")
        }
    }







    // 根据费用编码带出费用名称
    function getFynameByFyno(phid,fun){
        $NG.execServer("getFynameByFyno", {phid},function(res){
            console.log(res);
            if(res.count ==0||!phid)return 
            const _data = JSON.parse(res.data)[0].extendObjects
            fun(_data)
        })
    }
    //时间计算(月份)
    function sumDate(start,end){
        const staDt = new Date(start).getTime()
        const endDt = new Date(end).getTime()
        const sum = endDt-staDt
        const month = Number(Number(sum)/1000/60/60/24/30).toFixed(2)
        return month
    }
    useBeforeClick(function ({ args }) {
        //按钮点击前事件
        console.log("save按钮点击");
        const _arrs = grid.getRows()
        console.log(_arrs)
        let _cache_index = _arrs.reduce((value,item,index)=>{
            if(Number(item.u_rent_prc>(Number(item.u_sjrzrs)||0)*(Number(item.u_zfbz)||0))){
                value.push(index+1)
            }
                return value
        },[])
        if(_cache_index.length>0){
            $NG.alert(`表体明细中第 ${_cache_index.join("、")} 行中，月租含税金额超出->人数*租房标准，不符合规范，请修改!!`)
            return false
        }else {return true}
    }, "save");
});

